package logic

import (
	"context"
	"fmt"

	"longbri/rpc/internal/svc"
	"longbri/rpc/mysql"
	"longbri/rpc/pb/dashboard"

	"github.com/zeromicro/go-zero/core/logx"
)

type ExceptCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewExceptCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExceptCodeLogic {
	return &ExceptCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ExceptCodeLogic) ExceptCode(in *dashboard.ReqExceptCode) (*dashboard.RspExceptCode, error) {
	// todo: add your logic here and delete this line
	fmt.Println(in.String())

	count := int32(in.Count)
	if in.Count <= 0 {
		count = 100
	} else if in.Count > 1000 {
		count = 1000
	}

	var rows []*mysql.ExceptNews
	var err error
	if in.Id <= 0 {
		rows, err = l.svcCtx.ExceptNewsModel.SelectLateast(l.ctx, count)
	} else {
		//查询指定id的记录
		rows, err = l.svcCtx.ExceptNewsModel.Select(l.ctx, in.Id, count, in.Ahead)
	}

	if err != nil {
		logx.Error(err)
		return nil, err
	}

	fmt.Printf("rows:%v\n", rows)

	var infos []*dashboard.ExceptCode
	for i := 0; i < len(rows); i++ {
		tmp := rows[i]
		infos = append(infos, &dashboard.ExceptCode{
			Id:       tmp.Id,
			Code:     tmp.Code,
			ExceptTs: uint64(tmp.ExceptTs.Unix()),
			//ExceptVol: uint32(tmp.ExceptVol),
			ExceptVol: uint32(tmp.Vol),
			NewsTitle: tmp.NewsTitle.String,
			NewsTs:    uint64(tmp.NewsTs.Time.Unix()),
			NewsFrom:  tmp.NewsFrom.String,
			NewsUrl:   tmp.NewsUrl.String,
		})
	}

	return &dashboard.RspExceptCode{
		CodeList: infos,
	}, nil
}
